import time

from appium.options.android import UiAutomator2Options
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.common.by import By


class CommonDriver:
    def get_driver(self):
        options = UiAutomator2Options()
        options.platform_name = "Android"
        options.platform_version = "7"
        options.app_package = "com.dangdang.buy2"
        options.app_activity = "com.dangdang.buy2.StartupActivity"
        options.no_reset = False
        options.unicode_keyboard = True
        options.udid = "127.0.0.1:21513"

        command_executor_url = "http://127.0.0.1:4723/wd/hub"

        driver = webdriver.Remote(command_executor=command_executor_url, options=options)

        driver.implicitly_wait(10)

        print("连接成功")

        return driver


if __name__ == '__main__':
    driver = CommonDriver().get_driver()
    driver.find_element(By.XPATH, '//android.widget.TextView[@resource-id="com.dangdang.buy2:id/tv_sure"]').click()
    driver.find_element(By.XPATH, '//android.widget.TextView[@resource-id="com.dangdang.buy2:id/tv_sure"]').click()
    driver.find_element(By.XPATH,
                        '//android.widget.TextView[@resource-id="com.dangdang.buy2:id/dialog_cancel_tv"]').click()
    try:
        # 获取屏幕的尺寸
        screen_size = driver.get_window_size()
        # 获取屏幕的宽度
        width = screen_size["width"]
        # 获取屏幕的高度
        height = screen_size["height"]

        # 定义滑动的起始和结束坐标
        start_x = width / 2
        start_y = height * 0.8
        end_x = width / 2
        end_y = height * 0.2

        # 执行滑动的操作
        driver.swipe(start_x, start_y, end_x, end_y)

        time.sleep(2)
    finally:
        driver.quit()
